using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace Husb.WinForm.Controls
{
    public class DataGridViewExImageListCell : DataGridViewImageCell
    {
        public DataGridViewExImageListCell()
            : base()
        {
        }

        public DataGridViewExImageListCell(bool valueIsIcon)
            : base(valueIsIcon)
        {
        }

        protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
        {
            if (this.OwningColumn != null && this.OwningColumn is DataGridViewExImageListColumn)
            {
                DataGridViewExImageListColumn clmn = (DataGridViewExImageListColumn)this.OwningColumn;
                if (clmn.Images != null && clmn.Images.Images.Count > 0)
                {
                    Size retVal = clmn.Images.ImageSize;
                    if (retVal.Width < 10)
                        return new Size(16, 16);
                    retVal.Width += 2;

                    return retVal;
                }
            }
            return base.GetPreferredSize(graphics, cellStyle, rowIndex, constraintSize);
        }

        protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
        {
            if (value == null)
                return value;

            if (!value.GetType().IsAssignableFrom(typeof(Image)))
            {
                if (this.OwningColumn is DataGridViewExImageListColumn)
                {
                    DataGridViewExImageListColumn clmn = (DataGridViewExImageListColumn)this.OwningColumn;
                    if (clmn.Images != null)
                    {
                        Image img = clmn.Images.Images[value.ToString()];
                        if (img == null)
                            img = clmn.Images.Images["NULL"];
                        return img;
                    }
                }
                else
                    return null;
            }
            else
                return base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context);

            return null;
        }
    } 
}
